package com.expect.admin.busmanagement.web;

import java.io.IOException;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.ModelAndView;

import com.expect.admin.busmanagement.service.BusService;
import com.expect.admin.busmanagement.service.vo.BusVo;
import com.expect.admin.config.Settings;
import com.expect.admin.service.AttachmentService;
import com.expect.admin.service.LcService;
import com.expect.admin.service.LcrzbService;
import com.expect.admin.service.RoleJdgxbGxbService;
import com.expect.admin.service.RoleService;
import com.expect.admin.service.UserService;
import com.expect.admin.service.vo.RoleJdgxbGxbVo;
import com.expect.admin.service.vo.UserVo;
import com.expect.admin.service.vo.component.FileResultVo;
import com.expect.admin.service.vo.component.ResultVo;
import com.expect.admin.utils.Base64Util;
import com.expect.admin.utils.JsonResult;
import com.expect.admin.utils.MyResponseBuilder;
import com.expect.admin.utils.StringUtil;

@Controller
@RequestMapping(value = "/admin/busManagement")
public class BusController {
	/**
	 * slf4j简单日志门面
	 */
	private final Logger log = LoggerFactory.getLogger(BusController.class);

	@Autowired
	private BusService busService;
	@Autowired
	private LcrzbService lcrzbService;
	@Autowired
	private LcService lcService;
	@Autowired
	private UserService userService;
	@Autowired
	private AttachmentService attachmentService;
	@Autowired
	private Settings settings;
	@Autowired
	private RoleService roleService;
	@Autowired
	private RoleJdgxbGxbService roleJdgxbGxbService;

	private final String viewName = "admin/busManagement/";

	/**
	 * 维保申请界面
	 */
	@RequestMapping(value = "/addManagement", method = RequestMethod.GET)
	public ModelAndView addManagement() {
		BusVo busVo = new BusVo();
		UserVo userVo = userService.getLoginUser();
		busVo.setUserName(userVo.getFullName());
		ModelAndView mv = new ModelAndView(viewName + "b_apply");
		mv.addObject("busVo", busVo);
		return mv;
	}

	/**
	 * 申请记录界面
	 */
	@GetMapping(value = "/applicationRecord")
	public ModelAndView applicationRecord(@RequestParam(name = "state", required = false) String state) {
		if (StringUtil.isBlank(state))
			state = "wtj";
		ModelAndView mv = new ModelAndView(viewName + "b_apply_record");
		UserVo userVo = userService.getLoginUser();
		RoleJdgxbGxbVo condition = roleJdgxbGxbService.getWjzt("application", "maintenance");
		// mv.addObject("busVoList",busService.getBusByUserIdAndCondition(userVo.getId(),condition.getJdId(),state));
		return mv;
	}

	/**
	 * 申请记录详情（可编辑）
	 */
	@RequestMapping("/applicationRecordDetailE")
	public ModelAndView applicationRecordDetailE(@RequestParam(name = "id", required = true) String busId) {
		ModelAndView mv = new ModelAndView(viewName + "b_apply_recordDetailE");
		// BusVo busVo = busService.getBusById(busId);
		// mv.addObject("busVo", busVo);
		return mv;
	}

	/**
	 * 申请记录详情（不可编辑）
	 */
	@RequestMapping("/applicationRecordDetailNE")
	public ModelAndView applicationRecordDetailNE(@RequestParam(name = "id", required = true) String busId) {
		ModelAndView mv = new ModelAndView(viewName + "b_apply_recordDetailNE");
		// BusVo busVo = busService.getBusById(busId);
		// mv.addObject("busVo", busVo);
		return mv;
	}

	/**
	 * 保存和提交申请
	 * saveWay的required=true【【【【暂时改成false调试】】】】
	 * @param busVo
	 * @param saveWay
	 * @param attachmentId
	 * @param response
	 * @throws IOException
	 */
	@RequestMapping(value = "/saveApplication", method = RequestMethod.POST)
	public void saveApplication(BusVo busVo, @RequestParam(name = "saveWay", required = false) String saveWay,
			@RequestParam(name = "fileId", required = false) String[] attachmentId, HttpServletResponse response)
			throws IOException {
		if (!busCheck(busVo, response))
			return;
		String message = StringUtil.equals(saveWay, "submit") ? "维保申请" : "申请保存";
		try {
			busService.newApplicationSave(busVo, saveWay, attachmentId);
		} catch (Exception e) {
			log.error("保存申请报错", e);
			MyResponseBuilder.writeJsonResponse(response, JsonResult.useDefault(false, message + "失败！").build());
		}
		MyResponseBuilder.writeJsonResponse(response, JsonResult.useDefault(true, message + "成功！").build());
	}

	/**
	 * 申请不能为空
	 * 
	 * @param busVo
	 * @param response
	 * @return 满足要求返回true，否则返回false
	 * @throws IOException
	 */
	private boolean busCheck(BusVo busVo, HttpServletResponse response) throws IOException {
		if (busVo == null) {
			log.error("试图保存空的申请");
			MyResponseBuilder.writeJsonResponse(response, JsonResult.useDefault(false, "申请失败，申请内容为空！").build());
			return false;
		}
		return true;
	}

	/**
	 * 更新申请内容
	 * 
	 * @param busVo
	 * @param attachmentId
	 * @param response
	 * @throws IOException
	 */
	/**
	 * @RequestMapping(value = "/updateApplication",method = RequestMethod.POST)
	 *                       public void updateApplication(BusVo busVo,
	 * @RequestParam(name = "fileId", required = false) String[] attachmentId,
	 *                    HttpServletResponse response) throws IOException {
	 *                    try{ busService.updateApplication(busVo,attachmentId);
	 *                    }catch(Exception e){ log.error("更新申请内容报错", e);
	 *                    MyResponseBuilder.writeJsonResponse(response,
	 *                    JsonResult.useDefault(false, "更新申请内容失败！").build()); }
	 *                    MyResponseBuilder.writeJsonResponse(response,
	 *                    JsonResult.useDefault(true, "更新申请内容成功！").build()); }
	 */
	/**
	 * 删除已提交的申请（软删除）
	 * 
	 * @param response
	 * @param id
	 * @throws IOException
	 */
	/**
	 * @PostMapping("/deleteApplication") public void
	 * deleteApplication(HttpServletResponse response,
	 * 
	 * @RequestParam(name = "id",required = true)String id) throws IOException{
	 *                    try{ busService.deleteApplication(id);
	 *                    }catch(Exception e){ log.error("删除申请失败未找到id为" + id +
	 *                    "的申请", e);
	 *                    MyResponseBuilder.writeJsonResponse(response,
	 *                    JsonResult.useDefault(false, "未找到要删除的申请！").build()); }
	 *                    MyResponseBuilder.writeJsonResponse(response,
	 *                    JsonResult.useDefault(true, "删除申请成功！").build()); }
	 */
	/**
	 * 申请附件上传
	 * 
	 * @param files
	 * @param request
	 * @return
	 */
	@RequestMapping(value = "uploadApplicationAttachment", method = RequestMethod.POST)
	@ResponseBody
	public ResultVo upload(MultipartFile files, HttpServletRequest request) {
		String path = settings.getAttachmentPath();
		path = Base64Util.decode(path);
		FileResultVo frv = attachmentService.save(files, path);
		return frv;
	}

	/**
	 * 已保存的申请的提交
	 * 
	 * @param id
	 * @param attachmentId
	 * @param response
	 * @throws IOException
	 */
	/**
	 * @PostMapping("/submitWtj") public void submitWtj(String id,
	 * 
	 * @RequestParam(name = "fileId",required = false) String[] attachmentId,
	 *                    HttpServletResponse response) throws IOException{ try{
	 *                    BusVo busVo = busService.getBusById(id); if(busVo ==
	 *                    null){ MyResponseBuilder.writeJsonResponse(response,
	 *                    JsonResult.useDefault(false, "未找到该申请").build());
	 *                    return; } // String nextCondition =
	 *                    lcService.getNextCondition(busVo.getLcbs(),
	 *                    currentCondition) }catch(Exception e){
	 *                    log.error("已保存的申请提交时报错", e);
	 *                    MyResponseBuilder.writeJsonResponse(response,
	 *                    JsonResult.useDefault(false, "申请提交失败，请重试！").build());
	 *                    } MyResponseBuilder.writeJsonResponse(response,
	 *                    JsonResult.useDefault(true, "申请提交成功！").build()); }
	 */
	/**
	 * 已保存未提交的申请的删除
	 * 
	 * @param id
	 * @param response
	 * @throws IOException
	 */
	/**
	 * @PostMapping("/deleteWtj") public void deleteWtj(String
	 * id,HttpServletResponse response) throws IOException{ try{
	 * if(StringUtil.isBlank(id)){ MyResponseBuilder.writeJsonResponse(response,
	 * JsonResult.useDefault(false, "申请提交失败，要删除的申请id为空").build()); return; }
	 * busService.delete(id); }catch(Exception e){ log.error("已保存申请提交时报错", e);
	 * MyResponseBuilder.writeJsonResponse(response,
	 * JsonResult.useDefault(false, "申请删除失败！").build()); }
	 * MyResponseBuilder.writeJsonResponse(response, JsonResult.useDefault(true,
	 * "申请删除成功！").build()); }
	 */
}
